<template>
  <div class="review-container">
    <el-alert v-if="error" type="error" show-icon :closable="false">{{ error.message }}</el-alert>
    <el-skeleton v-if="loading" :rows="10" animated />

    <el-table v-else :data="products" style="width: 100%" border stripe>
      <el-table-column prop="productId" label="商品ID" width="100" align="center" />
      
      <el-table-column label="商品封面" width="120" align="center">
        <template #default="{ row }">
          <img 
            v-if="row.product_cover_image"
            :src="apiBase + '/product_images/' + row.product_cover_image"
            class="product-image"
            alt="商品封面"
          />
          <img
            v-else
            src="/placeholder-image.jpg"
            class="product-image"
            alt="暂无图片"
          />
        </template>
      </el-table-column>

      <el-table-column prop="productName" label="商品名称" min-width="180" />
      
      <el-table-column label="价格" width="120" align="right">
        <template #default="{ row }">
          ¥{{ row.productPrice.toFixed(2) }}
        </template>
      </el-table-column>

      <el-table-column prop="productStock" label="库存" width="100" align="center" />

      <el-table-column label="上架状态" width="120" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.productOnlineStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { getToken } from '@/utils/storage.js'
import { ElMessage, ElLoading } from 'element-plus'

interface Product {
  productId: string
  productName: string
  productPrice: number
  productStock: number
  product_cover_image?: string
  productOnlineStatus: number
}

const products = ref<Product[]>([])
const loading = ref(true)
const error = ref<Error | null>(null)
const apiBase = ref(import.meta.env.VITE_API_BASE || '')

const fetchProducts = async () => {
  try {
    loading.value = true
    const token = getToken()
    
    const response = await axios.get(`${apiBase.value}/product/all`, {
      headers: { Authorization: `Bearer ${token}` }
    })

    products.value = response.data.filter((p: Product) => p != null)
  } catch (err) {
    error.value = err as Error
    ElMessage.error('获取审核商品失败')
  } finally {
    loading.value = false
  }
}

const handleStatusChange = async (product: Product) => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  try {
    const token = getToken()
    if (!token) {
      throw new Error('请先登录管理员账号')
    }
    
    const response = await axios.put(`${apiBase.value}/product/onlineStatus`, {
      productId: product.productId,
      productOnlineStatus: product.productOnlineStatus
    }, {
      headers: { 
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (response.status === 200) {
      ElMessage.success('状态更新成功')
      await fetchProducts()
    } else {
      throw new Error(response.data?.message || '状态更新失败')
    }
  } catch (err) {
    const error = err as Error
    ElMessage.error(error.message || '状态更新失败')
    console.error('接口调用失败:', {
      message: error.message,
      stack: error.stack,
      requestData: {
        productId: product.productId,
        productOnlineStatus: product.productOnlineStatus
      },
      timestamp: new Date().toISOString()
    })
    // 回滚状态
    product.productOnlineStatus = product.productOnlineStatus === 1 ? 0 : 1
    // 强制更新视图
    products.value = [...products.value]
  } finally {
    loadingInstance.close()
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.review-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
  padding: 4px;
  background: #f5f5f5;
  border-radius: 4px;
}
</style>